package com.gpframework.framework.logging;

import com.gpframework.common.utils.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhuzhiou
 * @date 2021/1/30 17:14
 */
@Component
@Slf4j
public class TraceIdHandlerInterceptor implements HandlerInterceptor {

    private static final String HTTP_HEADER_GP_TRACE_ID = "X-GP-Trace-ID";

    private static final String GP_TRACE_ID_VARIABLE_NAME = "gpTraceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(HTTP_HEADER_GP_TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = IdUtils.randomUuid();
        }
        MDC.put(GP_TRACE_ID_VARIABLE_NAME, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(GP_TRACE_ID_VARIABLE_NAME);
    }
}
